#include <boost/bind.hpp>
#include "net_server.h"
#include "udp_socket.h"
#include "tcp_socket.h"

NetServer::NetServer(void) : m_acceptor(m_io_service)
{
}

NetServer::~NetServer(void)
{
}

bool NetServer::StartListenOn(WORD port)
{
	TcpSocket *socket = CreateTcpSocket();
	if(!socket)
		return false;

	m_acceptor.async_accept(socket->socket(),
		boost::bind(&NetServer::HandleAccept, this,
		boost::asio::placeholders::error, socket));

	return true;
}

bool NetServer::StartUdpRecvOn(WORD port)
{
	UdpSocket *socket = CreateUdpSocket();
	if(!socket)
		return false;

	if(!socket->Bind(port))
	{
		DeleteSocket(socket);
		return false;
	}

	if(!socket->Run())
	{
		DeleteSocket(socket);
		return false;
	}

	return true;
}

void NetServer::HandleAccept(const boost::system::error_code &error,
							 TcpSocket *socket)
{
	if(!error)
	{
		socket->Run();
	}
}